﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Vit.Caching
{
    public class CacheManagerFactory
    {
        private static object cacheManagerLock = new object();
        private static Dictionary<string, ICacheManager> cacheManagers = new Dictionary<string,ICacheManager>(StringComparer.OrdinalIgnoreCase);

        public static T GetCacheManager<T>(string cacheManagerName) where T : class, ICacheManager, new()
        {
            lock (cacheManagerLock)
            {
                if (cacheManagers.ContainsKey(cacheManagerName))
                    return cacheManagers[cacheManagerName] as T;
            }
            T cm = new T();
            cm.Initialize(cacheManagerName);

            lock (cacheManagerLock)
            {
                if (!cacheManagers.ContainsKey(cacheManagerName))
                    cacheManagers.Add(cacheManagerName, cm);
            }

            return cm;
        }

        public static void RegisterCacheManager<T>(T cacheManager) where T : class, ICacheManager, new()
        {
            lock (cacheManagerLock)
            {
                if (cacheManagers.ContainsKey(cacheManager.Name))
                    cacheManagers[cacheManager.Name] = cacheManager;
                else
                    cacheManagers.Add(cacheManager.Name, cacheManager);
            }
        }

        public static void RemoveCacheManager(string cacheManagerName)
        {
            lock (cacheManagerLock)
            {
                if (cacheManagers.ContainsKey(cacheManagerName))
                    cacheManagers.Remove(cacheManagerName);
            }
        }
    }
}
